import axios from 'axios'
import Vue from 'vue'
import store from '../store'

Vue.prototype.$http = axios

axios.defaults.headers.post['Content-Type']
    = 'application/x-www-form-urlencoded'

if (process.env.NODE_ENV === 'development') {
    axios.defaults.baseURL = '/api'
} else {
    axios.defaults.baseURL = 'http://testweb.biaoshi360.cn'
}

// 请求拦截器
axios.interceptors.request.use(
    config => {
        const { data, method } = config
        if (method === 'post') {
            let url = ''
            const curTeam = store.state.curTeam
            const info = {
                userToken: store.state.token
            }
            if(curTeam && curTeam.company_id) {
                info.company_id = curTeam.company_id
            }
            const params = Object.assign({}, data, info)
            Object.keys(params).forEach((key, i) => {
                url += `${i === 0 ? '' : '&'}${key}=${params[key]}`
            })
            config.data = url
        }
        return config
    },
    error => {
        Promise.reject(error)
        console.log(error)
    }
)

// 响应拦截器
axios.interceptors.request.use(
    response => response,
    error => Promise.reject(error)
)

export default axios
